package com.zjitc.controller;

import com.github.pagehelper.PageInfo;
import com.zjitc.common.Constant;
import com.zjitc.model.*;
import com.zjitc.service.*;
import com.zjitc.utils.MD5Utils;
import com.zjitc.utils.UUIDUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/24 17:06
 * @description:
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
  public static final Integer count=10;
  @Autowired
  private UserService userService;

  @Autowired
  private CategoryService categoryService;

  @Autowired
  private ProductService productService;

  @Autowired
  private OrderService orderService;

  @Autowired
  private CartService cartService;

  @Autowired
  private CollectionService collectionService;

  /**
   * 用户管理
   */

  @RequestMapping("/login")
  public String  login(@RequestParam(name = "username") String username,
                    @RequestParam(name = "password") String password,
                    HttpSession session) {
    password= MD5Utils.md5(password);
    User users=userService.login(username,password);
    if (users == null) {
      session.setAttribute("msg", "用户名和密码不匹配,请重新登录");
      return "/admin/index.jsp";
    } else {
      if (Constant.USER_IS_ADMINISTRAROR != users.getState()) {
        session.setAttribute("msg", "该用户不是管理员，不能进入管理员系统，即将跳转到用户登录页面");
        return "/jsp/login.jsp";
      }
      session.setAttribute("us", users);
     return  "/admin/home.jsp";
    }
  }

  @RequestMapping("/adminFindAllUser")
  public String findAllUsers(
      @RequestParam(name = "pageNum",defaultValue = "1")Integer pageNum,
      Model model){
    List<User> users=userService.findAllUser(pageNum,count);
    PageInfo<User> pageInfo=new PageInfo<User>(users);
    model.addAttribute("page",pageInfo);
    model.addAttribute("user",users);
    return "/admin/user/list.jsp";
  }

  @RequestMapping("/findWhereUserBeEdit")
  public String findUser(@RequestParam(name = "uid")String uid,
      Model model){
    User user=userService.findUser(uid);
    model.addAttribute("user",user);
    return "/admin/user/edit.jsp";
  }

  @RequestMapping("/adminEditUser")
  public String adminEditUser(
      @ModelAttribute("user") User user){
    userService.editUser(user);
    return "forward:/admin/adminFindAllUser.do";
  }

  @RequestMapping("/adminDeleteUser")
  public String adminDelete(@RequestParam(name = "uid")String uid){
    userService.deleteUser(uid);
    return "forward:/admin/adminFindAllUser.do";
  }

  /**
   * 分类管理
   */

  @RequestMapping("/adminCategoryFindAll")
  public String findAllCategory(Model model){
    List<Category> categories=categoryService.findAllCategory();
    model.addAttribute("categories",categories);
    return "/admin/category/list.jsp";
  }

  @RequestMapping("/editWhatCategory")
  public String editCategory(@RequestParam(name = "cid")String cid,
      Model model){
    Category category=categoryService.findByCid(cid);
    model.addAttribute("category",category);
    return "/admin/category/edit.jsp";
  }

  @RequestMapping("/adminEditCategory")
  public String adminEditCategory(@ModelAttribute("category")Category category){
    categoryService.editCategory(category);
    return "forward:/admin/adminCategoryFindAll.do";
  }

  @RequestMapping("/adminDeleteCategory")
  public String deleteCategory(@RequestParam(name = "cid")String cid){
    categoryService.deleteCategory(cid);
    return "forward:/admin/adminCategoryFindAll.do";
  }

  @RequestMapping("/adminAddCategory")
  public String addCategory(@RequestParam(name = "cname")String cname){
    Category category=new Category();
    category.setCid(UUIDUtils.getId());
    category.setCname(cname);
    categoryService.addCategory(category);
    return "forward:/admin/adminCategoryFindAll.do";
  }
  /**
   * 商品管理
   */

  @RequestMapping("/adminFindAllProduct")
  public String findAllProduct(
      @RequestParam(name = "pageNum",defaultValue = "1")Integer pageNum,
      Model model){
    List<Product> products=productService.findAllProduct(pageNum,count);
    PageInfo<Product> pageInfo=new PageInfo<Product>(products);
    model.addAttribute("page",pageInfo);
    model.addAttribute("product",products);
    return "/admin/product/list.jsp";
  }

  @RequestMapping("/adminEditWhatProduct")
  public String editProduct(@RequestParam(name = "pid")String pid,
      Model model){
        Product product=productService.findByPid(pid);
        List<Category> categories=categoryService.findAllCategory();
        model.addAttribute("product",product);
        model.addAttribute("categories",categories);
        return "/admin/product/edit.jsp";
  }

  @RequestMapping(value = "/adminEditProduct",method = RequestMethod.POST)
  public String editP(
          @RequestParam(name ="pid")String pid,
          @RequestParam (name = "pname")String pname,
          @RequestParam(name = "is_hot")Integer is_hot,
          @RequestParam(name = "market_price")Double market_price,
          @RequestParam(name = "shop_price")Double shop_price,
          @RequestParam(name = "pimage")MultipartFile pimage,
          @RequestParam(name = "cid")String cid,
          @RequestParam(name = "pdesc")String pdesc,
          HttpServletRequest request,
          Model model) throws IOException {
    Product product=new Product();
    if(!pimage.isEmpty()){
      String path=request.getServletContext().getRealPath("upload/");
      String filename=pimage.getOriginalFilename();
      File filepath=new File(path, filename);
      if (!filepath.getParentFile().exists()){
        filepath.getParentFile().mkdirs();
      }
      pimage.transferTo(new File(path+File.separator+filename));
      product.setPid(pid);
      product.setPname(pname);
      product.setIs_hot(is_hot);
      product.setMarket_price(market_price);
      product.setShop_price(shop_price);
      product.setPimage(request.getContextPath()+"upload/"+filename);
      product.setCid(cid);
      product.setPdesc(pdesc);
      productService.editProduct(product);
      model.addAttribute("product",product);
      return "forward:/admin/adminFindAllProduct.do";
    }
    return null;
  }

  @RequestMapping("/adminDeleteProduct")
  public String deleteProduct(@RequestParam(name = "pid")String pid){
    Product product = productService.findByPid(pid);
    if (product!=null) {
      List<OrderItem> order=orderService.findByPid(pid);
      Product collections=collectionService.findByPid(pid);
      Cart cart=cartService.findByPid(pid);
      if(order!=null) {
        orderService.deletePid(pid);
      }
      if(cart!=null){
        cartService.findByPid(pid);
      }
      if(collections!=null){
        collectionService.deletecollection(pid);
      }
        productService.deleteProduct(pid);
        return "forward:/admin/adminFindAllProduct.do";
    }
    return "/404.jsp";
  }

  @RequestMapping("/adminSelectAllCategory")
  public String selectCategory(Model model){
    List<Category> categories=categoryService.findAllCategory();
    model.addAttribute("categories",categories);
    return "/admin/product/add.jsp";
  }

  @RequestMapping("/adminAddProduct")
  public String addProduct(@RequestParam(name = "pname")String pname,
      @RequestParam(name = "is_hot")Integer is_hot,
      @RequestParam(name = "market_price")Double market_price,
      @RequestParam(name = "shop_price")Double shop_price,
      @RequestParam(name = "pimage")MultipartFile pimage,
      @RequestParam(name = "cid")String cid,
      @RequestParam(name = "pdesc")String pdesc,
      HttpServletRequest request,
      Model model) throws IOException {
    Product product=new Product();
    if(!pimage.isEmpty()) {
      String path = request.getServletContext().getRealPath("upload/");
      String filename = pimage.getOriginalFilename();
      File filepath = new File(path, filename);
      if (!filepath.getParentFile().exists()) {
        filepath.getParentFile().mkdirs();
      }
      pimage.transferTo(new File(path+File.separator+filename));
      product.setPid(UUIDUtils.getId());
      product.setPname(pname);
      product.setIs_hot(is_hot);
      product.setMarket_price(market_price);
      product.setShop_price(shop_price);
      product.setPimage(request.getContextPath()+"upload/"+filename);
      product.setCid(cid);
      product.setPdesc(pdesc);
      productService.addProduct(product);
      model.addAttribute("product",product);
      return "forward:/admin/adminFindAllProduct.do";
    }
    return  null;
  }
  /**
   * 订单管理
   */

  @RequestMapping("/adminOrderList")
  public String findAllOrders(
      @RequestParam(name = "pageNum",defaultValue = "1")Integer pageNum,
      Model model){
    List<Order> orders=orderService.findAllOrders(pageNum,count);
    PageInfo<Order> pageInfo=new PageInfo<Order>(orders);
    model.addAttribute("page",pageInfo);
    model.addAttribute("orders",orders);
    return "/admin/order/list.jsp";
  }

  @RequestMapping("/getDetailByOid")
  public String getDetail(@RequestParam(name = "oid")String oid,
      Model model){
        Order order=orderService.findByOid(oid);
        model.addAttribute("order",order);
        return "/admin/order/orderItem.jsp";
  }

  @RequestMapping("/findAllByState")
  public String findAllByState(@RequestParam(name = "state")Integer state,
      @RequestParam(name = "pageNum",defaultValue = "1")Integer pageNum,
      Model model){
    List<Order> orders=orderService.findAllByState(state,pageNum,count);
    PageInfo<Order> pageInfo=new PageInfo<Order>(orders);
    model.addAttribute("orders",orders);
    model.addAttribute("page",pageInfo);
    return "/admin/order/orderState.jsp";
  }

  @RequestMapping("/delivery")
  public String delivery(@RequestParam(name = "oid")String oid,Model model){
    Order order=orderService.findByOid(oid);
    model.addAttribute("order",order);
    return "/admin/order/delivery.jsp";
  }

  @RequestMapping("/sendGoods")
  public String sendGoods(@RequestParam(name = "oid")String oid,
                          @RequestParam(name = "express")String express){
    Order order = orderService.findByOid(oid);
    Integer state = order.getState();
    orderService.updateSend(oid,express,state);
    return "forward:/admin/adminOrderList.do";
  }
}
